package org.grayrabbit.cms.publish.generate.factory;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.constant.DictionaryStaticValues;
import org.grayrabbit.cms.entity.Admin;
import org.grayrabbit.cms.entity.Content;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.publish.api.Generatable;
import org.grayrabbit.cms.publish.generate.ContentGenerater;
import org.grayrabbit.cms.publish.generate.Generater;
import org.grayrabbit.cms.publish.generate.MultiGenerater;

import freemarker.template.Configuration;

/**
 * @author Administrator
 * @version 1.0
 * @created 15-����-2011 10:43:13
 */
public class ContentGeneraterFactory implements GeneraterFactory {
	private Configuration configuration;
	private List<Content> contents = new ArrayList<Content>();
	private String rootPath;
	private Generatable generatable;
	private Site site;
	private Admin admin;

	public ContentGeneraterFactory(Configuration configuration, Site site, List<Content> contents, String rootPath, 
			Generatable generatable, Admin admin) {
		this.configuration = configuration;
		this.contents = contents;
		this.rootPath = rootPath;
		this.site = site;
		this.generatable = generatable;
		this.admin = admin;
	}

	public ContentGeneraterFactory(Configuration configuration, Site site, String rootPath, 
			Generatable generatable, Admin admin) {
		this.configuration = configuration;
		this.rootPath = rootPath;
		this.site = site;
		this.generatable = generatable;
		this.admin = admin;
	}

	public ContentGeneraterFactory(Configuration configuration, Content content, String rootPath, Generatable generatable, Admin admin) {
		this.configuration = configuration;
		this.contents.add(content);
		this.rootPath = rootPath;
		this.generatable = generatable;
		this.admin = admin;
	}

	public void finalize() throws Throwable {

	}

	public Generater create() {
		List<Generater> list = new ArrayList<Generater>();
		boolean taxPreFlag = false;
		for (Content content : contents) {
			String path = "";
			if ("LinkContent".equals(content.getContextType())) {

			}
			else {
				if (!StringUtils.isNotBlank(content.getContentTpl())) {
					path = content.getCategory().getCatDefaultContentTpl().substring((File.separator + rootPath).length());
				}
				else {
					path = content.getContentTpl().substring((File.separator + rootPath).length());
				}
				list.add(new ContentGenerater(configuration, site, path, content, generatable, admin));
			}
		}

		if (list.size() == 1)
			return list.get(0);
		if (list.size() == 2 && taxPreFlag)
			return list.get(0);
		return new MultiGenerater(list);
	}

}